#!/usr/bin/env python
'''
DocIndexer Parsers class.
'''
import parse_text, parse_html, parse_antiword, parse_pdf, parse_odt, parse_docx, parse_mp3
from common import EDocIndexer, mime_type, safe_print

class Parsers(object):

    builtin_parsers = [parse_text.Parser,
                       parse_html.Parser,
                       parse_pdf.Parser,
                       parse_antiword.Parser,
                       parse_odt.Parser,
                       parse_docx.Parser,
                       parse_mp3.Parser,
                      ]

    def __init__(self):
        self.parsers = []

    def open1(self,parser):
        '''Register instance of single parser class.'''
        if parser not in [p.__class__ for p in self.parsers]:
            self.parsers.append(parser())

    def open(self):
        '''Register instances of all available built-in parser classes.'''
        for parser in self.builtin_parsers:
            # Silently skip parsers that aren't available.
            try:
                self.parsers.append(parser())
            except EDocIndexer:
                pass

    def close(self):
        for parser in self.parsers:
            parser.close()

    def mimeparser(self,mimetype):
        '''Return parser instance that handles mimetype else None.'''
        # Search parsers in reverse registration order so newer parsers can
        # can be registered to override older ones.
        for parser in self.parsers[::-1]:
            if parser.handles(mimetype):
                return parser
        else:
            return None

    def fileparser(self,filename):
        '''Return parser instance that handles filename else None.'''
        mimetype = mime_type(filename)
        return self.mimeparser(mimetype)

    def text(self,filename):
        '''Return text content of file filename.'''
        # TODO: Allow filename to be file type object and add optional mimetype
        # argument.
        parser = self.fileparser(filename)
        if parser is not None:
            return parser.text(filename)
        else:
            raise EDocIndexer,'no parser'


if __name__ == '__main__':
    import os, sys
    if len(sys.argv) != 2:
        safe_print('usage: %s filename' % os.path.basename(sys.argv[0]))
        sys.exit(1)
    parsers = Parsers()
    filename = sys.argv[1]
    try:
        parsers.open()
        try:
            safe_print(parsers.text(filename))
        finally:
            parsers.close()
        sys.exit(0)
    except EDocIndexer, e:
        print 'failed:',e
        sys.exit(1)

# vim: ts=4 sw=4:
